<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { Search, Refresh, Bottom } from "@element-plus/icons-vue";
import { getLoginLogByPage, getAllLoginLog } from "@/api";
import type { FormInstance } from "element-plus";
import { utils, writeFile } from "xlsx";
import { ElMessage } from "element-plus";

/**
 * 导出excel
 */
interface DataItem {
  readonly id: string;
  [propName: string]: string;
}

interface Columns {
  dataKey: string;
  key: string;
  title: string;
  width?: number;
  [propName: string]: string | number;
}

const generateColumns = (length = 10, prefix = "column-", props?: any) =>
  Array.from({ length }).map((_, columnIndex) => ({
    ...props,
    key: `${prefix}${columnIndex}`,
    dataKey: `${prefix}${columnIndex}`,
    title: `Column ${columnIndex}`,
    width: 150
  }));

const generateData = (
  columns: ReturnType<typeof generateColumns>,
  length = 200,
  prefix = "row-"
) =>
  Array.from({ length }).map((_, rowIndex) => {
    return columns.reduce(
      (rowData, column, columnIndex) => {
        rowData[column.dataKey] = `Row ${rowIndex} - Col ${columnIndex}`;
        return rowData;
      },
      {
        id: `${prefix}${rowIndex}`,
        parentId: null
      }
    );
  });

const Excelcolumns = generateColumns(10);
const data = generateData(Excelcolumns, 1000);

const exportExcel = async () => {
  loading.value = true;
  try {
    // 获取所有登录日志数据
    const res = await getAllLoginLog();
    if (res.status === "success") {
      // 构建表头和数据
      const titleList = columns.map(col => col.label);
      const exportData = res.data.map(item => {
        return columns.map(col => {
          // 特殊处理状态字段
          if (col.prop === "login_status") {
            return item[col.prop] === 1 ? "成功" : "失败";
          }
          // 特殊处理可能过长的字段，保持原样导出
          if (["login_description", "login_ua"].includes(col.prop)) {
            return item[col.prop];
          }
          return item[col.prop];
        });
      });

      // 添加表头
      exportData.unshift(titleList);

      // 创建工作表
      const workSheet = utils.aoa_to_sheet(exportData);

      // 设置列宽
      const colWidth = columns.map(col => {
        if (["login_description", "login_ua"].includes(col.prop)) {
          return { wch: 50 }; // 较长的文本列
        }
        if (["login_time", "created_at"].includes(col.prop)) {
          return { wch: 20 }; // 时间列
        }
        return { wch: 15 }; // 默认列宽
      });
      workSheet["!cols"] = colWidth;

      const workBook = utils.book_new();
      utils.book_append_sheet(workBook, workSheet, "登录日志");

      // 导出文件
      const now = new Date();
      const fileName = `登录日志_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, "0")}${now.getDate().toString().padStart(2, "0")}.xlsx`;
      writeFile(workBook, fileName);

      ElMessage.success("导出成功");
    }
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败");
  } finally {
    loading.value = false;
  }
};

interface LogRecord {
  id: number;
  admin_id: number;
  login_time: string;
  login_ip: string;
  login_ua: string;
  login_status: number;
  login_description: string;
  created_at: string;
}

// 表格数据
const dataList = ref<LogRecord[]>([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 15, 20],
  background: true
});

// 查询表单数据
const queryForm = reactive({
  start_at: "",
  end_at: "",
  admin_id: "",
  status: "",
  description: ""
});

// 状态选项
const statusOptions = [
  { label: "成功", value: 1 },
  { label: "失败", value: 0 }
];

// 定义表格列
const columns = [
  {
    label: "ID",
    prop: "id",
    width: 80,
    align: "center"
  },
  {
    label: "管理员ID",
    prop: "admin_id",
    width: 100,
    align: "center"
  },
  {
    label: "登录时间",
    prop: "login_time",
    width: 180,
    align: "center"
  },
  {
    label: "登录IP",
    prop: "login_ip",
    width: 140,
    align: "center"
  },
  {
    label: "登录状态",
    prop: "login_status",
    width: 100,
    align: "center",
    slot: true
  },
  {
    label: "登录描述",
    prop: "login_description",
    minWidth: 50,
    align: "center",
    showOverflowTooltip: true
  },
  {
    label: "用户代理",
    prop: "login_ua",
    minWidth: 50,
    align: "center",
    showOverflowTooltip: true
  },
  {
    label: "创建时间",
    prop: "created_at",
    width: 180,
    align: "center"
  }
];

// 获取日志列表数据
const fetchLogList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      start_at: queryForm.start_at,
      end_at: queryForm.end_at,
      admin_id: queryForm.admin_id,
      status: queryForm.status,
      description: queryForm.description
    };

    const res = await getLoginLogByPage(params);
    if (res.status === "success") {
      dataList.value = res.data.records;
      pagination.total = res.data.pagination.total;
    }
  } catch (error) {
    console.error("获取登录日志失败:", error);
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  queryForm.start_at = "";
  queryForm.end_at = "";
  queryForm.admin_id = "";
  queryForm.status = "";
  queryForm.description = "";
  handleQuery();
};

// 查询方法
const handleQuery = () => {
  pagination.currentPage = 1;
  fetchLogList();
};

// 分页处理
const onSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchLogList();
};

const onCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchLogList();
};

onMounted(() => {
  fetchLogList();
});
</script>

<template>
  <div class="login-log-container">
    <el-card v-loading="loading">
      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="mb-[20px]">
        <div class="flex flex-wrap gap-4">
          <el-form-item label="管理员ID">
            <el-input
              v-model="queryForm.admin_id"
              placeholder="请输入管理员ID"
              clearable
              class="!w-[180px]"
            />
          </el-form-item>
          <el-form-item label="登录状态">
            <el-select
              v-model="queryForm.status"
              placeholder="请选择状态"
              clearable
              class="!w-[180px]"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="登录描述">
            <el-input
              v-model="queryForm.description"
              placeholder="请输入登录描述"
              clearable
              class="!w-[180px]"
            />
          </el-form-item>
          <el-form-item label="登录时间">
            <div class="flex items-center">
              <el-date-picker
                v-model="queryForm.start_at"
                type="datetime"
                placeholder="开始时间"
                class="!w-[180px]"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
              <span class="mx-2">至</span>
              <el-date-picker
                v-model="queryForm.end_at"
                type="datetime"
                placeholder="结束时间"
                class="!w-[180px]"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
          </el-form-item>
        </div>

        <div
          class="flex items-center justify-between w-full mt-4 border-t pt-4"
        >
          <div class="flex gap-2">
            <el-button type="primary" @click="handleQuery">
              <el-icon class="mr-2"><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetForm">
              <el-icon class="mr-2"><Refresh /></el-icon>重置
            </el-button>
            <el-button type="primary" @click="exportExcel">
              <el-icon class="mr-2"><Bottom /></el-icon>导出
            </el-button>
          </div>
        </div>
      </el-form>

      <!-- 表格部分 -->
      <el-table
        v-loading="loading"
        :data="dataList"
        style="width: 100%"
        border
        stripe
        table-layout="auto"
      >
        <el-table-column label="ID" prop="id" width="80" align="center" />
        <el-table-column
          label="管理员ID"
          prop="admin_id"
          width="100"
          align="center"
        />
        <el-table-column
          label="登录时间"
          prop="login_time"
          width="180"
          align="center"
        />
        <el-table-column
          label="登录IP"
          prop="login_ip"
          width="140"
          align="center"
        />
        <el-table-column
          label="登录状态"
          prop="login_status"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="row.login_status === 1 ? 'success' : 'danger'"
              effect="light"
            >
              {{ row.login_status === 1 ? "成功" : "失败" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="登录描述"
          prop="login_description"
          min-width="50"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="用户代理"
          prop="login_ua"
          min-width="50"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="created_at"
          width="180"
          align="center"
        />
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes"
          :background="pagination.background"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.login-log-container {
  box-sizing: border-box;
  width: 100%;
  padding: 20px;

  :deep(.el-form) {
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }

  :deep(.el-table) {
    width: 100% !important;

    .el-table__body-wrapper {
      overflow-x: auto;
    }

    // 设置表格行高
    .el-table__row {
      height: 55px; // 增加行高
    }

    // 设置表头行高
    .el-table__header-row {
      height: 55px; // 增加表头行高
    }

    // 调整单元格内容垂直居中
    .cell {
      display: flex;
      align-items: center;
      padding: 8px;
      line-height: 24px;
    }
  }
}
</style>
